package com.ruoyi.system.apiService;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.GeneratorUtil;
import com.ruoyi.common.utils.OSSUplodFile;
import com.ruoyi.common.utils.QRCodeUtil;
import com.ruoyi.system.domain.ZsyyQrCode;
import com.ruoyi.system.dto.ParkQrCodeDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

@Service
public class CodeService {
	/*二维码跳转的url*/
	@Value("${code.url}")
	private String url;
	// 嵌入二维码的图片路径
	@Value("${code.imgpath}")
	private String imgPath;
	//生成的二维码的路径
	private String destPath;
	//嵌入二维码的图片保存地址
	private String imgPath_new;
	//获取AccessToken路径
	private static final String AccessToken_URL
		= "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";//小程序id
	//获取二维码路径
	private static final String WxCode_URL
		= "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=ACCESS_TOKEN";//小程序密钥

	/**
	 * 生成二维码
	 * @param cartNo
	 * @param channelsNo
	 * @return
	 */
	public String addCode(String cartNo,String channelsNo) throws Exception {
		URL url = new URL(imgPath);
		// 打开URL连接
		HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
		// 得到URL的输入流
		InputStream input = con.getInputStream();
		// 设置数据缓冲
		byte[] bs = new byte[1024 * 2];
		// 读取到的数据长度
		int len;
		// 输出的文件流保存图片至本地
		File file = new File("");
		String uuid = GeneratorUtil.genFileName();
		String filePath = file.getCanonicalPath()+"\\msdwQrcode\\";//获取当前项目路径+保存的路径
		imgPath_new=filePath+uuid+".jpg"; //图标保存地址
		OutputStream os = new FileOutputStream(filePath+uuid+".jpg");
		while ((len = input.read(bs)) != -1) {
			os.write(bs, 0, len);
		}

		destPath=filePath+uuid+".jpg"; //二维码存放地址

		String url_new=this.url+"?cartNo="+cartNo+"&channelsNo="+channelsNo;

		QRCodeUtil.encode(url_new,imgPath_new,destPath,true);
		InputStream stream=new FileInputStream(destPath);
		String path = OSSUplodFile.inputUplaod(stream); //上传到服务器
//        deleteFile(uuid+".jpg");   //上传后删除文件
		os.close();
		input.close();
		stream.close();
		return path;
	}

	/**
	 * 生成停车场二维码
	 * @param type
	 * @param parkQrCodeDto
	 * @return
	 * @throws Exception
	 */
	public String addParkQrCode(Integer type, ParkQrCodeDto parkQrCodeDto) throws Exception {
		URL url = new URL(imgPath);
		// 打开URL连接
		HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
		// 得到URL的输入流
		InputStream input = con.getInputStream();
		// 设置数据缓冲
		byte[] bs = new byte[1024 * 2];
		// 读取到的数据长度
		int len;
		// 输出的文件流保存图片至本地
		File file = new File("");
		String filePath = file.getCanonicalPath()+"\\msdwQrcode\\";//获取当前项目路径+保存的路径
//		String filePath = "root\\msdwAdmin\\msdwQrcode\\";//获取当前项目路径+保存的路径
		String uuid = GeneratorUtil.genFileName();
		imgPath_new=filePath+uuid+".jpg"; //图标保存地址
		OutputStream os = new FileOutputStream(filePath+uuid+".jpg");
		while ((len = input.read(bs)) != -1) {
			os.write(bs, 0, len);
		}

		destPath=filePath+uuid+".jpg"; //二维码存放地址
		String url_new="type="+type+"&info="+parkQrCodeDto;
//        String passUrl_new = MD5UtilByPark.convertMD5(url_new); //执行MD5加密字符串

		QRCodeUtil.encode(url_new,imgPath_new,destPath,true);
		InputStream stream=new FileInputStream(destPath);
		String path = OSSUplodFile.inputUplaod(stream); //上传到服务器
        boolean flag =  deleteFile(uuid+".jpg");   //上传后删除文件
		os.close();
		input.close();
		stream.close();
		return path;
	}



	/**
	 * 删除单个文件
	 * @param   sPath    被删除文件的文件名
	 * @return 单个文件删除成功返回true，否则返回false
	 */
	public static boolean deleteFile(String sPath) {
		boolean flag = false;
		try {
			// 输出的文件流保存图片至本地
			File file = new File("");
			String filePath = file.getCanonicalPath()+"\\msdwQrcode\\";//获取当前项目路径+保存的路径
//			String filePath = "root\\msdwAdmin\\msdwQrcode\\";//获取当前项目路径+保存的路径
			File file1 = new File(filePath+sPath);
			// 路径为文件且不为空则进行删除
			if (file1.isFile() && file1.exists()) {
				file1.delete();
				flag = true;
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
		return flag;
	}

	/**
	 * 生成后台购买二维码支付二维码
	 * @param orderNo
	 * @return
	 */
	public String addQrCode(String orderNo) throws Exception {
		URL url = new URL("https://ygyxj.oss-cn-shenzhen.aliyuncs.com/" +
			"park/ce1c4a01492a4b138f99852b3ca4ba93.png");
		// 打开URL连接
		HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
		// 得到URL的输入流
		InputStream input = con.getInputStream();
		// 设置数据缓冲
		byte[] bs = new byte[1024 * 2];
		// 读取到的数据长度
		int len;
		// 输出的文件流保存图片至本地
		File file = new File("");
		String uuid = GeneratorUtil.genFileName();
		String filePath = file.getCanonicalPath()+"\\msdwQrcode\\";//获取当前项目路径+保存的路径
		imgPath_new=filePath+uuid+".jpg"; //图标保存地址
		OutputStream os = new FileOutputStream(filePath+uuid+".jpg");
		while ((len = input.read(bs)) != -1) {
			os.write(bs, 0, len);
		}

		destPath=filePath+uuid+".jpg"; //二维码存放地址
		String url_new="https://kshht.gzmsdw.cn/api/unionpay/wxgzhPay?orderNo="+orderNo;
//        String url_new="http://fxwite.natappfree.cc/api/unionpay/wxgzhPay?orderNo="+orderNo;

		QRCodeUtil.encode(url_new,imgPath_new,destPath,true);
		InputStream stream=new FileInputStream(destPath);
		String path = OSSUplodFile.inputUplaod(stream); //上传到服务器
//        deleteFile(uuid+".jpg");   //上传后删除文件
		os.close();
		input.close();
		stream.close();
		return path;
	}

	/**
	 * 用于获取access_token
	 * @return  access_token
	 * @throws Exception
	 */
	public static String getAccessToken(String appid,String secret) throws Exception {
		String requestUrl = AccessToken_URL.replace("APPID",appid).replace("APPSECRET",secret);
		URL url = new URL(requestUrl);
		// 打开和URL之间的连接
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setRequestMethod("POST");
		// 设置通用的请求属性
		connection.setRequestProperty("Content-Type", "application/json");
		connection.setRequestProperty("Connection", "Keep-Alive");
		connection.setUseCaches(false);
		connection.setDoOutput(true);
		connection.setDoInput(true);

		// 得到请求的输出流对象
		DataOutputStream out = new DataOutputStream(connection.getOutputStream());
		out.writeBytes("");
		out.flush();
		out.close();

		// 建立实际的连接
		connection.connect();
		// 定义 BufferedReader输入流来读取URL的响应
		BufferedReader in = null;
		if (requestUrl.contains("nlp"))
			in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "GBK"));
		else
			in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
		String result = "";
		String getLine;
		while ((getLine = in.readLine()) != null) {
			result += getLine;
		}
		in.close();
		JSONObject jsonObject = JSON.parseObject(result);
		String accesstoken=jsonObject.getString("access_token");
		return accesstoken;
	}

	/**
	 * 生成微信二维码
	 *
	 */
	public static String addWxCode(String accessToken, ZsyyQrCode qrCodes, String toPath) {
		String path = "";
		String filePath = "c://msdwQrcode/";
		File file = new File(filePath);
		if (!file.exists()) {
			file.mkdirs();
		}
		String picName = UUID.randomUUID().toString() + ".jpg";
		String savePath = filePath+picName;
		try
		{
			String wxCodeURL = WxCode_URL.replace("ACCESS_TOKEN",accessToken);
			URL url = new URL(wxCodeURL);
			HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
			httpURLConnection.setRequestMethod("POST");// 提交模式
			// conn.setConnectTimeout(10000);//连接超时 单位毫秒
			// conn.setReadTimeout(2000);//读取超时 单位毫秒
			// 发送POST请求必须设置如下两行
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());

//            String param = "qrId="+qrCodes.getId()+"&communityId="+
//                    qrCodes.getCommunityId();

			String param = qrCodes.getId().toString();

			// 发送请求参数
			JSONObject paramJson = new JSONObject();
			paramJson.put("scene", param);
			paramJson.put("page", toPath); //小程序暂未发布我没有带page参数
			paramJson.put("width", 430);
			paramJson.put("is_hyaline", true);
			paramJson.put("auto_color", true);

			//line_color生效
			paramJson.put("auto_color", false);
			JSONObject lineColor = new JSONObject();
			lineColor.put("r", 0);
			lineColor.put("g", 0);
			lineColor.put("b", 0);
			paramJson.put("line_color", lineColor);

			printWriter.write(paramJson.toString());
			// flush输出流的缓冲
			printWriter.flush();
			//开始获取数据
			BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
			OutputStream os = new FileOutputStream(new File(savePath));
			int len;
			byte[] arr = new byte[1024];
			while ((len = bis.read(arr)) != -1)
			{
				os.write(arr, 0, len);
				os.flush();
			}
			File getFile = new File(savePath);
			InputStream stream=new FileInputStream(getFile);
			path = OSSUplodFile.inputUplaod(stream); //上传到服务器

			os.close();
			stream.close();

			//删除本地文件
			File filePaths = new File("c://msdwQrcode/"+picName);
			filePaths.delete();
			File getParentFile = new File(filePath);
			getParentFile.delete();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return path;
	}
}
